'use strict';
/**
    自定义报表    
*/
var reportForm = angular.module('reportForm', ['tm.pagination', 'Common', 'knowledgeSelector', 'PensonSelector', 'knowledgebaseS', "btnconqitk"])
.controller('reportFormController', ['$scope', "$rootScope", '$interval', 'RequestTrainService', '$state', 'Msg', 'MsgCon', '$q', 'requestStatisticService', 'sysUserInfo', 'T', function ($scope, $rootScope, $interval, RTS, $state, Msg, MsgCon, $q, RS, sysUserInfo, T) {

    $scope.btnlist = { addinfo: false, editinfo: false, delinfo: false };
    $rootScope.btnTab = "index.Train.ReportForm";

    $scope.showData = false; //显示列表  true,显示数据
    $scope.initAdd = function () {
        // 配置参数
        $scope.getUserDataParams = {
            tableName: "", //表名
            userid: sysUserInfo.getuserinfo().user_ID,
            userName: sysUserInfo.getuserinfo().user_Name,
            orgid: sysUserInfo.getuserinfo().organization_ID, // 企业id        
            powerLV: sysUserInfo.getuserinfo().powerLV,
            departID: sysUserInfo.getuserinfo().orgStr, //所负责部门
            startDate: "",
            endDate: "",
            jsonusercodeparam: { // 查询属性
                orglist: [],    // 需要筛选的部门id集合
                rolelist: [],   // 需要筛选的角色id集合
                grouplist: [],  // 需要筛选的用户组id集合
                User_ID: [],    // 需要筛选的用户id集合
                Address: "",    // 地址
                Email: "",      // 邮箱
                User_Account: "",   // 登录账号
                User_Code: "",  // 编号
                User_Name: "",  // 姓名
                paramsort: "",  // 排序 格式 userid desc,user_name asc
                ResultExamId: [],    // 需要筛选的试卷id集合
                CourseId: [],   // 需要筛选的课程id集合
                ArrangeId: [], // 需要筛选的任务id集合
                KnowledgeList: [] //  通过知识分类筛选人员
            },
            headjson: {   //  显示属性  null 为不显示
                Address: 1, // 地址
                Email: 1,   // 邮箱
                User_Account: 1,    // 登录账号
                user_no: 1, // 编号
                User_Name: "1", // 姓名
                CreateDate: "1",    // 创建时间
                endDate: "1",   // 账号结束日期
                endTime: 1, // 账号结束时间
                startDate: 1,   // 账号开始日期
                startTime: 1,   // 账号形如时间
                Phone: 1,   // 手机 
                organization_Name: 1,   // 企业名称
                //     powerLV: "1",   // 权限
                //      user_Img: "1",  // 头像
                User_Sex: "1",  // 性别
                graduate_school: "1",  //毕业院校
                nation: "1",  //毕业院校
                birthDate: "1", //出生年月
                education: "1", //学历
                Organizationlist: "1",  // 组织机构集合
                Rolelist: "1",  // 角色集合
                Grouplist: "1", // 用户组集合
                LastLogininTime: "1", // 最后登录时间
                state: "1",  // 用户状态
                LoginCount: "1", //登录次数
              //  KnowledgeList: "1"   // 人员所涉及的知识分类
                integral: "1"//积分
            }

        }
        $scope.knowConfig = {   // 配置知识选择器的参数
            menu: [], //["structure","courseware","examination","task"],
            windowSize: "standard", //  窗口类型 standard:标准(默认)  mini :迷你
            kssMore: true, //知识结构 是否多选
            kssList: [],    // 知识结构选中列表                
            kscMore: true, // 课程列表是否多选
            kscList: [], // 课程选中列表
            kseMore: true, // 试卷列表是否多选
            kseList: [], // 试卷选中列表 
            ksrMore: true, // 任务是否多选
            ksrList: [], // 任务列表
            isShow: false,  // 显示知识选择器
            callbackParams: {   //回调操作型参数 选择填写参数   配合回调方法使用
                isClose: true
            }
        };
    }
    $scope.initAdd(); //初始新增参数
    /**************弹框*****************/
    // 显示信息弹框
    $scope.visibleUserInfo = false;
    // header用户信息 集合
    $scope.headerInfoList = [{ name: "user_no", displayName: T.T("number"), flag: false },
                             { name: "User_Name", displayName: T.T("FullName"), flag: false },
                             { name: "Phone", displayName: T.T("phone"), flag: false },
                             { name: "User_Sex", displayName: T.T("Gender"), flag: false },
                             { name: "graduate_school", displayName: T.T("University"), flag: false },
                             { name: "nation", displayName: T.T("Nation"), flag: false },
                             { name: "birthDate", displayName: T.T("DateOfBirth"), flag: false },
                             { name: "education", displayName: T.T("Education"), flag: false },
                             { name: "Email", displayName: T.T("Email"), flag: false },
                             { name: "Address", displayName: T.T("Address"), flag: false },
                             { name: "User_Account", displayName: T.T("AccountNumber"), flag: false },
                             { name: "Organizationlist", displayName: T.T("Organization"), flag: false },
                             { name: "Rolelist", displayName: T.T("Role"), flag: false },
                             { name: "Grouplist", displayName: T.T("UserGroup"), flag: false },
                             { name: "organization_Name", displayName: T.T("EnterpriseName"), flag: false },
                             { name: "CreateDate", displayName: T.T("CreationTime"), flag: false, type: 'date' },
                             { name: "startDate", displayName: T.T("LoggedStartDate"), flag: false },
                             { name: "endDate", displayName: T.T("LoggedEndDate"), flag: false },
                             { name: "startTime", displayName: T.T("LoggedStartTime"), flag: false },
                             { name: "endTime", displayName: T.T("LoggedEndTime"), flag: false },
                             { name: "LastLogininTime", displayName: T.T("LastLogonTime"), eName: "LastLogininTime", flag: false },
                             { name: "state", displayName: T.T("UserStatus"), flag: false },
                             { name: "integral", displayName: T.T("integral"), flag: false },
//                             { name: "KnowledgeList", displayName: T.T("KnowledgeClassification"), eName: "KnowledgeList", flag: false },
                             { name: "LoginCount", displayName: T.T("NumberOfLogins"), flag: false },
                        ];
    // data 数据
    $scope.headerDataList = [
                            { type: 1, name: "Learntimecount", displayName: T.T("TotalLearningDuration"), flag: false },
                            { type: 1, name: "CourseCollectionsCount", displayName: T.T("CollectionCourseNumber"), flag: false },
                            { type: 1, name: "KeSumCount", displayName: T.T("NumberOfCoursesLearned"), flag: false },
                            { type: 1, name: "KeCompleteCount", displayName: T.T("NumberOfCoursesCompleted"), flag: false },

                            { type: 2, name: "ExamResultPassCount", displayName: T.T("PassingNumberOfExaminations"), flag: false },
                            { type: 2, name: "ExamResultCount", displayName: T.T("TestTimes"), flag: false },

//                            { type: 3, name: "TaskarrangeSumCount", displayName: T.T("TotalNumberOfTasks"), flag: false },
                            { type: 3, name: "TaskarrangeCompleteCount", displayName: T.T("MissionCompletionNumber"), flag: false },

                            { type: 4, name: "QuestionsCompleteCount", displayName: T.T("IHaveDoneSomeQuestionNumber"), flag: false },
//                            { type: 4, name: "ShouldQuestionsCount", displayName: T.T("TotalAnswerQuestions"), flag: false },
//                            { type: 4, name: "QuestionsCompleteRate", displayName: T.T("CompletionRateOfTopic"), flag: false },
                            { type: 4, name: "QuestionsBingoCount", displayName: T.T("AnswerLogarithm"), flag: false },
                            { type: 4, name: "QuestionsBingoRate", displayName: T.T("QuestionAnswerRate"), flag: false },
                            ];

    // 数据标记为全选
    $scope.selAll = function (dataList) {
        var flag = true;
        if (dataList[0].flag) {
            flag = false;
        }
        angular.forEach(dataList, function (data, index) {
            data.flag = flag;
        });
    }
    // 弹框
    $scope.openVisible = function () {
        // 基本信息 标记选中
        angular.forEach($scope.headerInfoList, function (data, index) {
            if ($scope.getUserDataParams.headjson[data.name] == "1") {
                data.flag = true;
            } else {
                data.flag = false;
            }
        });
        //  数据查询
        angular.forEach($scope.headerDataList, function (data, index) {
            if ($scope.getUserDataParams.headjson[data.name] == "1") {
                data.flag = true;
            } else {
                data.flag = false;
            }
        });
        $scope.initAdd();
        $scope.visibleUserInfo = true;
    }

    // 确定选择
    $scope.saveVisible = function () {

        // 基本信息
        angular.forEach($scope.headerInfoList, function (data, index) {
            if (data.flag) {
                $scope.getUserDataParams.headjson[data.name] = "1";
            } else {
                $scope.getUserDataParams.headjson[data.name] = null;
            }
        });
        //  数据查询
        angular.forEach($scope.headerDataList, function (data, index) {
            if (data.flag) {
                $scope.getUserDataParams.headjson[data.name] = "1";
            } else {
                $scope.getUserDataParams.headjson[data.name] = null;
            }
        });
        /**** 各种分类******/
        $scope.headDateBase();
        $scope.addExport();
    }
    // 处理分类
    $scope.headDateBase = function () {
        // 添加显示的列            
        if ($scope.isNull($scope.knowConfig.ksrList) || $scope.knowConfig.ksrList.length <= 0) {
            $scope.getUserDataParams.headjson.LookupTaskArrangeList = null;
        } else {
            $scope.getUserDataParams.headjson.LookupTaskArrangeList = "1";
        }
        angular.forEach($scope.knowConfig.ksrList, function (data, index) {
            // 请求参数
            $scope.getUserDataParams.jsonusercodeparam.ArrangeId.push(data.id);
        });
        // 课程
        if ($scope.isNull($scope.knowConfig.kscList) || $scope.knowConfig.kscList.length <= 0) {
            // 添加显示的列
            $scope.getUserDataParams.headjson.LookupCourseList = null;
        } else {
            $scope.getUserDataParams.headjson.LookupCourseList = "1";
        }
        angular.forEach($scope.knowConfig.kscList, function (data, index) {
            // 请求参数
            $scope.getUserDataParams.jsonusercodeparam.CourseId.push(data.course_Id);
        });
        // 试卷
        if ($scope.isNull($scope.knowConfig.kseList) || $scope.knowConfig.kseList.length <= 0) {
            // 添加显示的列
            $scope.getUserDataParams.headjson.LookupExamResultList = null;
        } else {
            // 添加显示的列
            $scope.getUserDataParams.headjson.LookupExamResultList = "1";
        }
        angular.forEach($scope.knowConfig.kseList, function (data, index) {
            // 请求参数
            $scope.getUserDataParams.jsonusercodeparam.ResultExamId.push(data.paperId);
        });
        // 需要筛选的知识id集合
        $scope.getUserDataParams.jsonusercodeparam.KnowledgeList = [];
        angular.forEach($scope.knowConfig.kssList, function (data, index) {
            $scope.getUserDataParams.jsonusercodeparam.KnowledgeList.push(data.knowledge_Id);
        });
        // 需要筛选的用户id集合
        $scope.getUserDataParams.jsonusercodeparam.User_ID = [];
        angular.forEach($scope.userInfoConfig.UserList, function (data, index) {
            $scope.getUserDataParams.jsonusercodeparam.User_ID.push(data.user_ID);
        });
        // 需要筛选的部门id集合
        $scope.getUserDataParams.jsonusercodeparam.orglist = [];
        angular.forEach($scope.userInfoConfig.userOrgList, function (data, index) {
            $scope.getUserDataParams.jsonusercodeparam.orglist.push(data.organization_ID);

        });
        // 需要筛选的用户组id集合
        $scope.getUserDataParams.jsonusercodeparam.grouplist = [];
        angular.forEach($scope.userInfoConfig.userGroupList, function (data, index) {
            $scope.getUserDataParams.jsonusercodeparam.grouplist.push(data.userGroup_ID);
        });
        // 需要筛选的角色id集合
        $scope.getUserDataParams.jsonusercodeparam.rolelist = [];
        angular.forEach($scope.userInfoConfig.userRoleList, function (data, index) {
            $scope.getUserDataParams.jsonusercodeparam.rolelist.push(data.roles_ID);
        });

         //公式的头formula
        if($scope.gsList.length>0){
            $scope.gsList.forEach(function(data,index){
                delete data.kseList;
                delete data.expList;
            });
            $scope.getUserDataParams.gsList=JSON.stringify($scope.gsList);
        }
       
        
    }
    //新增的loading
    $scope.isSaveBtn = false;

    //新增方法
    $scope.addExport = function () {

        if ($scope.getUserDataParams.tableName.length <= 0) {
            Msg.warning("请输入报表名称！");
            return;
        }
        $scope.isSaveBtn = true;
        var addparam = angular.copy($scope.getUserDataParams);
        if ($scope.getUserDataParams.powerLV != 3) {
            addparam.orgStr = "";
        }
        addparam.headjson = JSON.stringify(addparam.headjson);
        addparam.jsonusercodeparam = JSON.stringify(addparam.jsonusercodeparam);

        RTS.addOrEditStatistics(addparam).then(function (response) {
            $scope.isSaveBtn = false;
            if (response.errorcode == "0") {
                Msg.success("保存成功！");
                $scope.closeVisible();
                $scope.initAdd(); //初始新增参数
                $scope.getTabList();
            } else if (response.errorcode == "22") {
                Msg.warning("表名已存在！");
            } else if (response.errorcode == "25") {
                Msg.warning(response.errormsg);
            } else {
                Msg.error("保存失败!")
            }
        }, function errorCallback() {
            $scope.isSaveBtn = false;
            console.log("连接服务器失败！");
        });
    }
    /*********************************************************************/
    // 选中个数
    $scope.checkAll = 0;
    // 单选
    $scope.singleCheck = function (item) {
        if (item.isSel) {
            $scope.checkAll--;
            item.isSel = false;
        } else {
            $scope.checkAll++;
            item.isSel = true;
        }
    }
    //全选
    $scope.selectAll = function () {
        $scope.selFlag = true;
        if ($scope.checkAll == $scope.tabList.length) { //已选
            $scope.selFlag = false;
            $scope.checkAll = 0;
        } else {
            $scope.selFlag = true;
            $scope.checkAll = $scope.tabList.length;
        }
        // 设置样式
        angular.forEach($scope.tabList, function (data, index, array) {
            data.isSel = $scope.selFlag;
        });
    }
    //查询参数
    $scope.tabparams = {
        orgid: sysUserInfo.getuserinfo().organization_ID,
		uid: sysUserInfo.getuserinfo().user_ID,
        pageSize: 10,
        pageIndex: 1
    };
    //查询第一步
    $scope.getTabList = function () {

        $scope.Loading = true;
        RTS.findTable($scope.tabparams).then(function (response) {
            $scope.Loading = false;
            if (response.errorcode == "0") {
				$scope.checkAll = 0;
                $scope.tabList = response.datas;
                $scope.tabpaginationConf.totalItems = response.numCount;
                $scope.tabpaginationConf.currentPage = response.pageIndex;
            } else {
                Msg.error("查询报表失败!")
            }
        }, function errorCallback() {
            $scope.Loading = false;
            console.log("连接服务器失败！");
        });
    }
    //  $scope.getTabList();
    $scope.params = {
        datetableName: "",
        count: "",
        statisticsId: "",
        selectString: [], //筛选条件
        andOr: "and",
        pageSize: 15,
        pageIndex: 1
    };

    //选择表，查看数据
    $scope.checkTable = function (item) {
        if (item.state != "2") {
            Msg.warning("数据正在统计中，请稍后。。。");
            return;
        }
        $scope.conditionList = [];
        $scope.showData = true;
        $scope.params.datetableName = item.datetableName;
        $scope.params.startDate=item.startDate;
        $scope.params.endDate=item.endDate;
        $scope.params.count = item.count;
        $scope.params.statisticsId = item.statisticsId;
        $scope.params.pageSize = 15;
        $scope.params.pageIndex = 1;
        // $scope.getList();
    }
    //初始新增条件
    $scope.initAddCondition = function () {
        //条件对象
        $scope.conditionParams = {
            colKey: "", //显示的名字
            colName: "", //列名
            opType: "", //条件，大于、等于
            colValue: "" //值
        };
    }

    $scope.initType = function () {
        //条件类型
        $scope.typeList = [
            { id: "1", name: T.T("BeEqualTo") },
            { id: "2", name: T.T("GreaterThanEqualToOrEqualTo") },
            { id: "3", name: T.T("LessThanEqualToOrEqual") },
            { id: "4", name: T.T("greaterThan") },
            { id: "5", name: T.T("lessThan") },
            { id: "6", name: T.T("Contain") },
            { id: "7", name: T.T("NotEqualTo") },
            { id: "8", name: T.T("DoNotContain") },
            { id: "9", name: T.T("empty") },
            { id: "10", name: T.T("NonEmpty") }
        ];
        $scope.conType = "string"; //当前添加的条件的类型
    }
    //更改属性
    $scope.changeAttr = function () {
        $scope.initType();

        //获取
        $scope.headList.forEach(function (data, index) {
            if (data.key == $scope.conditionParams.colKey) {
                $scope.conditionParams.colName = data.name;
            }
        });
        $scope.conditionParams.colValue = "";
        //int类型
        if ($scope.conditionParams.colName.indexOf("数") != -1 || $scope.conditionParams.colName.indexOf("率") != -1 || $scope.conditionParams.colName.indexOf("时长") != -1) {
            $scope.conType = "int";
        } else if ($scope.conditionParams.colName.indexOf("日期") != -1) {
            $scope.conType = "date";
            $scope.typeList.splice(5, 1);
            $scope.typeList.splice(7, 1);
        } else if ($scope.conditionParams.colName.indexOf("创建时间") != -1) {
            $scope.conType = "datetime";
            $scope.typeList.splice(5, 1);
            $scope.typeList.splice(7, 1);
        } else if ($scope.conditionParams.colName.indexOf("时间") != -1) {
            $scope.conType = "time";
            $scope.typeList.splice(5, 1);
            $scope.typeList.splice(7, 1);
        } else {
            $scope.conType = "string";
        }
    }
    //获取日期
    $scope.getDate = function (id) {
        if(id=="startDate"){
            $scope.getUserDataParams.startDate=document.getElementById(id).value;
        }else if(id=="endDate"){
            $scope.getUserDataParams.endDate=document.getElementById(id).value;
        }else{
            $scope.conditionParams.colValue = document.getElementById(id).value;
        }
    }
    $scope.initAddCondition();
    $scope.initType();
    //删除条件
    $scope.delCondition = function (num) {
        $scope.conditionList.splice(num, 1);
        $scope.getList();
    }
    //条件的集合
    $scope.conditionList = [];
    //条件筛选框
    $scope.showCondition = false;
    //条件筛选框的打开关闭
    $scope.closeCondition = function () {
        $scope.showCondition = !$scope.showCondition;
    }
    //条件筛选框的查询
    $scope.searchCondition = function () {
        $scope.closeCondition();
        var condition = angular.copy($scope.conditionParams);
        condition.colName = $scope.getNameByKey(condition.colKey);
        $scope.conditionList.push(condition);
        $scope.getList();
    }
    //返回列表
    $scope.backList = function () {
        $scope.showData = false;
    }
    $scope.headList = [];
    //查询报表的数据
    $scope.getList = function () {
        $scope.params.selectString = $scope.conditionList;
        $scope.headList = [];
        $scope.Loading = true;
        RTS.findStatisticsTable($scope.params).then(function (response) {
            $scope.Loading = false;
            if (response.errorcode == "0") {
                $scope.List = response.datas;
                var list = response.data.split(",");
                list.forEach(function (data, index) {
                    var a = data.trim();
                    if (a == "id" || a == "User_ID") {

                    } else {
                        var name = $scope.getNameByKey(a);
                        if (name.length <= 0) {
                            name = a;
                        }
                        $scope.headList.push({ name: name, value: index, key: a });
                    }
                });

                $scope.paginationConf.totalItems = response.numCount;
                $scope.paginationConf.currentPage = response.pageIndex;
            } else if (response.errorcode == "73") {
                Msg.warning("正在统计中，请稍后。。。");
            } else {
                Msg.error("查询数据失败!")
            }
        }, function errorCallback() {
            $scope.Loading = false;
            console.log("连接服务器失败！");
        });
    }

    //获取名字
    $scope.getNameByKey = function (key) {

        var name = "";
        $scope.headerInfoList.forEach(function (data, index) {
            if (data.name == key.trim()) {
                name = data.displayName;
            }
        });
        if (name.length <= 0) {
            $scope.headerDataList.forEach(function (data, index) {
                if (data.name == key) {
                    name = data.displayName;
                }
            });
        }
        return name;
    }
    //配置分页
    $scope.tabpaginationConf = {
        currentPage: 1, //$location.search().currentPage ? $location.search().currentPage :  当前页码
        totalItems: 0,  // 总的记录数
        itemsPerPage: 10, // 每页显示多少条        
        perPageOptions: [10, 20],   // 每页显示记录数        
        onChange: function () {
            $scope.tabpaginationConf.currentPage = $scope.tabpaginationConf.currentPage == 0 ? 1 : $scope.tabpaginationConf.currentPage;
            $scope.tabparams.pageIndex = $scope.tabpaginationConf.currentPage;
            $scope.tabparams.pageSize = $scope.tabpaginationConf.itemsPerPage;
            $scope.getTabList();
        }
    }
    //配置分页
    $scope.paginationConf = {
        currentPage: 1, //$location.search().currentPage ? $location.search().currentPage :  当前页码
        totalItems: 0,  // 总的记录数
        itemsPerPage: 15, // 每页显示多少条        
        perPageOptions: [15, 30],   // 每页显示记录数        
        onChange: function () {
            $scope.paginationConf.currentPage = $scope.paginationConf.currentPage == 0 ? 1 : $scope.paginationConf.currentPage;
            $scope.params.pageIndex = $scope.paginationConf.currentPage;
            $scope.params.pageSize = $scope.paginationConf.itemsPerPage;
            $scope.getList();
        }
    }

    //编辑
    $scope.EditTable = function () {
        var delObj;
        var count = 0;
        angular.forEach($scope.tabList, function (data, index, array) {
            if (data.isSel) {
                count++;
                delObj = data;
            }
        });
        if (count <= 0) {
            Msg.warning("请选择一条数据！");
            return;
        } else if (count > 1) {
            Msg.warning("只能选择一条数据！");
            return;
        } else if (delObj.state == 0 || delObj.state == 1) {
            Msg.warning("数据未统计完成，请耐心等待！");
            return;
        }
        $scope.getUserDataParams.tableName = delObj.tableName;
        $scope.getUserDataParams.statisticsId = delObj.statisticsId;
        $scope.getUserDataParams.jsonusercodeparam = JSON.parse(delObj.jsonusercodeparam);
        $scope.getUserDataParams.headjson = JSON.parse(delObj.headjson);

        var addparam = angular.copy($scope.getUserDataParams);
        if ($scope.getUserDataParams.powerLV != 3) {
            addparam.orgStr = "";
        }
        addparam.headjson = delObj.headjson;
        addparam.jsonusercodeparam = delObj.jsonusercodeparam;

        RTS.addOrEditStatistics(addparam).then(function (response) {
            $scope.Loading = false;
            if (response.errorcode == "0") {
                Msg.success("开始统计。。。");
                $scope.getTabList();
            } else if (response.errorcode == "22") {
                Msg.warning("表名已存在！");
            } else {
                Msg.error("统计失败!")
            }
        }, function errorCallback() {
            $scope.Loading = false;
            console.log("连接服务器失败！");
        });
        //        //  数据查询
        //        angular.forEach($scope.headerInfoList, function (data, index) {
        //            for (var key in $scope.getUserDataParams.headjson) {
        //                if (data.name == key) {
        //                    if ($scope.getUserDataParams.headjson[key] == "1") {
        //                        data.flag = true;
        //                    } else {
        //                        data.flag = false;
        //                    }
        //                }
        //            }
        //        });

        //        //  数据查询
        //        angular.forEach($scope.headerDataList, function (data, index) {
        //            for (var key in $scope.getUserDataParams.headjson) {
        //                if (data.name == key) {
        //                    if ($scope.getUserDataParams.headjson[key] == "1") {
        //                        data.flag = true;
        //                    } else {
        //                        data.flag = false;
        //                    }
        //                }
        //            }
        //        });
        //        $scope.visibleUserInfo = true;
    }
    //删除
    $scope.DeleteTable = function () {
        var ids = [];
        angular.forEach($scope.tabList, function (data, index, array) {
            if (data.isSel) {
                ids.push(data.statisticsId);
            }
        });
        if (ids.length <= 0) {
            Msg.warning("请选择一条数据！");
            return;
        }
        //提示框
        MsgCon.delnoicon().then(function (flag) {   // 删除弹框
            if (flag) {
                $scope.Loading = true;
                RTS.deleteStatistics({ statisticsId: ids.join(","), powerLv: sysUserInfo.getuserinfo().powerLV, userid: sysUserInfo.getuserinfo().user_ID }).then(function (response) {
                    $scope.Loading = false;
                    if (response.errorcode == "0") {
                        Msg.success("删除成功！");
                        $scope.getTabList();
                    } else {
                        Msg.error("删除失败!")
                    }
                }, function errorCallback() {
                    $scope.Loading = false;
                    console.log("连接服务器失败！");
                });
            }
        });
    }
    //导出
    $scope.exportTable = function () {
        var tabN = "";
        $scope.tabList.forEach(function (data, index) {
            if (data.statisticsId == $scope.params.statisticsId) {
                tabN = data.datetableName;
            }
        });
        $scope.exportCenter(tabN);

    }
    $scope.exportCenter = function (name) {
        var lang = window.localStorage.lang;
        if (lang == null || lang == undefined || lang == "") {
            lang = 'cn';
            window.localStorage.lang = lang;
        }
        var head = "";

        $scope.headList.forEach(function (data, index) {
            head += (head.length > 0 ? ',' : "") + data.name;
        });

        //查询学员信息与考勤信息
        RTS.exportStatistics({ datatableName: name, znOren: head }).then(function (data) {
            if (data.errorcode == "0") {
                window.location = data.errormsg;
            }
            else if (data.errorcode == "73") {
                setTimeout(function () {
                    $scope.exportCenter(name);
                }, 10000);
                Msg.warning("正在统计请稍后..");
            } else {
                Msg.error(T.T("RequestDataError"));
            }
        });
    }
    /********************************************************************/

    // 查询知识结构下面的课程和试卷
    $scope.selKnowCouExa = function (knowledgeids) {
        var def = $q.defer();
        var params = {
            knowledgeids: knowledgeids,
            pageIndex: 1,
            pageSize: 10000,
            userid: sysUserInfo.getuserinfo().user_ID
        };
        RS.findArrangeStage(params).then(function (data) {
            if (data.errorcode == 0) {
                def.resolve(data.datas);
            } else {
                def.resolve([]);
            }
        });
        return def.promise;
    }

    // 关闭选择
    $scope.closeVisible = function () {
        $scope.visibleUserInfo = false;
    }

    /*******调用知识选择器**********/
    //配置知识选择器
    $scope.knowConfig = {   // 配置知识选择器的参数
        menu: [], //["structure","courseware","examination","task"],
        windowSize: "standard", //  窗口类型 standard:标准(默认)  mini :迷你
        kssMore: true, //知识结构 是否多选
        kssList: [],    // 知识结构选中列表                
        kscMore: true, // 课程列表是否多选
        kscList: [], // 课程选中列表
        kseMore: true, // 试卷列表是否多选
        kseList: [], // 试卷选中列表 
        ksrMore: true, // 任务是否多选
        ksrList: [], // 任务列表
        isShow: false,  // 显示知识选择器
        callbackParams: {   //回调操作型参数 选择填写参数   配合回调方法使用
            isClose: true
        }
    };

    // 打开知识选择器
    $scope.openKnowledgeSelector = function (item) {
        $scope.knowConfig.menu[0] = item;
        $scope.knowConfig.isShow = true;
    }

    // 回调函数 虽然很消耗性能但是还是要进行这样操作 遍历任务中的课程试卷
    $scope.onCallback = function () {
        angular.forEach($scope.knowConfig.ksrList, function (data, index) {
            var arrKnoList = [];
            angular.forEach(JSON.parse(data.arragetype), function (item, index) {
                arrKnoList = arrKnoList.concat(item.kssList);
            });

            var knowledgeids = [];
            // 请求数据            
            angular.forEach(arrKnoList, function (sdata, index, array) {
                // 追加id
                //data.value += sdata.knowledge_Id + ',';
                var objknow = {};
                var knowId = "";
                var type = "";
                //有课程1
                if (sdata.know_select_course != undefined && sdata.know_select_course) {
                    type = "1";
                    knowId = sdata.knowledge_Id;
                }
                //有试卷2
                if (sdata.know_select_exam != undefined && sdata.know_select_exam) {
                    type += type.length > 0 ? ",2" : "2";
                    knowId = sdata.knowledge_Id;
                }
                //如果有课程  和  试卷
                if (type.length > 0 && knowId.length > 0) {
                    objknow = { knowledgeId: knowId, type: type };
                    knowledgeids.push(objknow);
                }
            });

            data.arrCouList = [];
            data.arrExaList = [];
            $scope.selKnowCouExa(knowledgeids).then(function (response) {
                if (!$scope.isNull(response) && response.length > 0) {
                    angular.forEach(response, function (item, index) {
                        if (item.style == "1") {  // 课程
                            data.arrCouList.push({ course_Id: item.courseId, course_Name: item.courseName });
                        }
                        if (item.style == "2") {  // 试卷
                            data.arrExaList.push({ paperId: item.paperId, paperName: item.paperName });
                        }
                    });
                }
            });
        });
    }

    // 删除选择器中的对象 flag 类型   0 课程   1 试卷  2 题库  3任务 4 用户 5 组织机构  6 用户组 7角色
    $scope.delItem = function (item, flag) {
        switch (flag) {
            case 0:
                angular.forEach($scope.knowConfig.kscList, function (data, index) {
                    if (item.course_Id == data.course_Id) {
                        $scope.knowConfig.kscList.splice(index, 1);
                    }
                });
                break;
            case 1:
                angular.forEach($scope.knowConfig.kseList, function (data, index) {
                    if (item.paperId == data.paperId) {
                        $scope.knowConfig.kseList.splice(index, 1);
                    }
                });
                break;
            case 2:
                angular.forEach($scope.knowConfig.kssList, function (data, index) {
                    if (item.knowledge_Id == data.knowledge_Id) {
                        $scope.knowConfig.kssList.splice(index, 1);
                    }
                });
                break;
            case 3:
                angular.forEach($scope.knowConfig.ksrList, function (data, index) {
                    if (item.id == data.id) {
                        $scope.knowConfig.ksrList.splice(index, 1);
                    }
                });
                break;
            case 4:
                angular.forEach($scope.userInfoConfig.UserList, function (data, index) {
                    if (item.user_ID == data.user_ID) {
                        $scope.userInfoConfig.UserList.splice(index, 1);
                    }
                });
                break;
            case 5:
                angular.forEach($scope.userInfoConfig.userOrgList, function (data, index) {
                    if (item.organization_ID == data.organization_ID) {
                        $scope.userInfoConfig.userOrgList.splice(index, 1);
                    }
                });
                break;
            case 6:
                angular.forEach($scope.userInfoConfig.userGroupList, function (data, index) {
                    if (item.userGroup_ID == data.userGroup_ID) {
                        $scope.userInfoConfig.userGroupList.splice(index, 1);
                    }
                });
                break;
            case 7:
                angular.forEach($scope.userInfoConfig.userRoleList, function (data, index) {
                    if (item.roles_ID == data.roles_ID) {
                        $scope.userInfoConfig.userRoleList.splice(index, 1);
                    }
                });
                break;
        }
    }
    /*********** 查询 *************/
    // 配置用户信息
    $scope.userInfoConfig = {
        ApiOpen: false,
        searchType: [],
        menu: [{ "id": "User" }, { "id": "Org" }, { "id": "Role" }, { "id": "Group"}],
        userOrgList: [],
        userGroupList: [],
        userRoleList: [],
        userAuthorityList: [],
        userOrgValues: [],
        userGroupValues: [],
        userRightValues: [],
        UserList: []
    }
    // 打开人员选择器
    $scope.openUserInfo = function (event) {
        $scope.userInfoConfig.ApiOpen = true;
        $scope.userInfoConfig.event = event;
    }

    // 查询全部
    $scope.getAllUserData = function () {
        // 处理查询参数
        $scope.getUserDataParams.jsonusercodeparam = { // 查询属性
            orglist: [],    // 需要筛选的部门id集合
            rolelist: [],   // 需要筛选的角色id集合
            grouplist: [],  // 需要筛选的用户组id集合
            starttime: "",  // 开始时间
            endtime: "",    // 截止时间
            User_ID: [],    // 需要筛选的用户id集合
            Address: "",    // 地址
            Email: "",      // 邮箱
            User_Account: "",   // 登录账号
            User_Code: "",  // 编号
            User_Name: "",  // 姓名
            paramsort: "",  // 排序 格式 userid desc,user_name asc
            ResultExamId: [],    // 需要筛选的试卷id集合
            CourseId: [],   // 需要筛选的课程id集合
            ArrangeId: [] // 需要筛选的任务id集合
        }

        // 初始化人员基本信息
        $scope.userInfoConfig = {
            ApiOpen: false,
            searchType: [],
            menu: [{ "id": "User" }, { "id": "Org" }, { "id": "Role" }, { "id": "Group"}],
            userOrgList: [],
            userGroupList: [],
            userRoleList: [],
            userAuthorityList: [],
            userOrgValues: [],
            userGroupValues: [],
            userRightValues: [],
            UserList: []
        }
        // 全局搜索清空一下
        $scope.selectContext = "";
        // 初始化知识分类
        $scope.knowConfig = {   // 配置知识选择器的参数
            menu: [], //["structure","courseware","examination","task"],
            windowSize: "standard", //  窗口类型 standard:标准(默认)  mini :迷你
            kssMore: true, //知识结构 是否多选
            kssList: [],    // 知识结构选中列表                
            kscMore: true, // 课程列表是否多选
            kscList: [], // 课程选中列表
            kseMore: true, // 试卷列表是否多选
            kseList: [], // 试卷选中列表 
            ksrMore: true, // 任务是否多选
            ksrList: [], // 任务列表
            isShow: false,  // 显示知识选择器
            callbackParams: {   //回调操作型参数 选择填写参数   配合回调方法使用
                isClose: true
            }
        };
        // 查询数据
        //  $scope.getUserDataList();
    }

    // 格式话时间
    Date.prototype.format = function (fmt) {
        var o = {
            "M+": this.getMonth() + 1,                 //月份 
            "d+": this.getDate(),                    //日 
            "h+": this.getHours(),                   //小时 
            "m+": this.getMinutes(),                 //分 
            "s+": this.getSeconds(),                 //秒 
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
            "S": this.getMilliseconds()             //毫秒 
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        return fmt;
    }
    // 判断是否为空
    $scope.isNull = function (data) {
        if (data == null || data == undefined || data == "") {
            return true;
        }
        return false;
    }

    //**************************************************************公式组合*************************************************************/

    $scope.gsList=[];
    var sortList=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];

     // 初始化知识分类
    $scope.gsConfig = {   // 配置知识选择器的参数
        menu: ["examination","externalpaper"],
        windowSize: "standard", //  窗口类型 standard:标准(默认)  mini :迷你           
        kseMore: true, // 试卷列表是否多选
        kseList: [], // 试卷选中列表 
        expMore:true,  // 外部试卷列表是否多选
        expList:[], // 外部试卷选中列表
        isShow: false,  // 显示知识选择器
        callbackParams: {   //回调操作型参数 选择填写参数   配合回调方法使用
            isClose: true
        }
    };

    //打开公式选择器
    $scope.openSelectGs=function(obj){
       //赋值
       if(obj!=undefined){
            $scope.gsConfig.kseList=obj.kseList;
            $scope.gsConfig.expList=obj.expList;
            $scope.gsConfig.paperObj=obj;
       }else{
            $scope.gsConfig.kseList=[];
            $scope.gsConfig.expList=[];
            delete $scope.gsConfig.paperObj;
       }
        $scope.gsConfig.isShow=!$scope.gsConfig.isShow;
    }
    //删除组合公式整个对象
    $scope.delGs=function(index){
        $scope.gsList.splice(index,1);
    }
    //公式选择后的回调
    $scope.onGsCallback=function(){
        
        var paperList=[];
        //赋值代号
        $scope.gsConfig.kseList.forEach(function(data,index){
            var dh=sortList[index];
            paperList.push({id:data.paperId,name:data.paperName,dh:dh,type:1});
        });
         //赋值代号
        $scope.gsConfig.expList.forEach(function(data,index){
            var dh=sortList[index+$scope.gsConfig.kseList.length];
            paperList.push({id:data.externalId,name:data.externalName,dh:dh,type:2});
        });

        //{kseList:"试卷列表",expList:"外部试卷列表",gs:"组合的公式"}   expList,kseList保存的时候会删除掉
        if($scope.gsConfig.paperObj!=undefined){
            $scope.gsConfig.paperObj.paperList=paperList;
        }else{
            $scope.gsList.push({paperList:paperList,gs:"",kseList:$scope.gsConfig.kseList,expList:$scope.gsConfig.expList});
        }

        
    }

    //删除公式item,删除的集合，id删除的索引
    $scope.delPaperObj=function(item,id){

        item.paperList.splice(id,1);
    }
    //向公式中插入的值
    $scope.newNumber=0;
    //组合公式
    $scope.addGS=function(str,item){
        item.gs=item.gs+str;
        $scope.newNumber=0;
    }
    $scope.delGS=function(item){
        item.gs="";
    }

} ])
